package com.caiden_micheal.dynamic.workflow.utils;

import com.caiden_micheal.base.constant.ProcessStatus;
import com.caiden_micheal.base.domain.workflow.ProcessEdge;
import com.caiden_micheal.dynamic.record.domain.DProcessRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson2.JSON;
import com.caiden_micheal.base.domain.workflow.ProcessNode;

import java.util.List;
import java.util.Objects;

public class NodeParsingTool {
    private static final Logger logger = LoggerFactory.getLogger(NodeParsingTool.class);

    public static List<ProcessNode> parseNodeList(String nodeStr) {
        try {
            List<ProcessNode> processNodeList = JSON.parseArray(nodeStr, ProcessNode.class);
            return processNodeList;
        } catch (Exception e) {
            logger.error(e.toString());
            return null;
        }
    }

    public static ProcessNode findById(String id, List<ProcessNode> processNodeList) {
        for (ProcessNode processNode : processNodeList) {
            if (Objects.equals(processNode.getId(), id)) {
                return processNode;
            }
        }
        return null;
    }

    public static void processNode(List<DProcessRecord> dProcessRecordList, List<ProcessNode> processNodeList, List<ProcessEdge> processEdgeList) {
        for (ProcessNode processNode : processNodeList) {
            for (DProcessRecord dProcessRecord : dProcessRecordList) {
                if (Objects.equals(dProcessRecord.getNodeId(), processNode.getId())) {
                    switch (dProcessRecord.getProcessResult()) {
                        case 0:
                            processNode.getProperties().setStatus(ProcessStatus.Completed.value);
                            EdgeParsingTool.processEnterEdge(processNode.getId(), ProcessStatus.Completed.value, processEdgeList, dProcessRecordList);
                            break;
                        case 1:
                            processNode.getProperties().setStatus(ProcessStatus.Rejected.value);
                            EdgeParsingTool.processEnterEdge(processNode.getId(), ProcessStatus.Rejected.value, processEdgeList, dProcessRecordList);
                            break;
                        case 2:
                            processNode.getProperties().setStatus(ProcessStatus.Processing.value);
                            EdgeParsingTool.processEnterEdge(processNode.getId(), ProcessStatus.Processing.value, processEdgeList, dProcessRecordList);
                            break;
                    }
                }
            }
        }


    }
}
